package com.woniu.bh.backstage.feign;

import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.io.IOException;

/**
 * @version: V1.0
 * @author: Xbao
 * @className: RestTemplateInterceptor
 * @packageName: com.woniu.bh.backstage.feign
 * @description:
 * @data: 2020-10-22 12:14
 */
//@Component
public class RestTemplateInterceptor implements ClientHttpRequestInterceptor {
    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
            throws IOException {
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String token = sra.getRequest().getHeader("X-Token");
        if(token != null && !token.trim().equals("")) request.getHeaders().add("X-Token", token);
        return execution.execute(request, body);
    }
}

